package com.sunyard.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.bo.org.*;
import com.sunyard.dal.dto.OrgTreeDTO;
import com.sunyard.dal.dto.OrganizationDTO;
import com.sunyard.dal.dto.SysPermissionDTO;
import com.sunyard.dal.entity.Car;
import com.sunyard.dal.entity.Organization;
import com.sunyard.dal.entity.Role;
import com.sunyard.dal.entity.SysLog;
import com.sunyard.dal.mapper.*;
import com.sunyard.manage.constant.TblLogConst;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.manage.service.OrganizationService;
import com.sunyard.manage.util.ValidatorUtils;
import com.sunyard.redisUtil.RedisUtils;
import com.sunyard.utils.DateUtil;
import com.sunyard.utils.DtoUtils;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jiy.fang
 * @ClassName OrganizationServiceImpl
 * @Description 机构管理
 * @date 2019/7/16 0:31
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private OperatorMapper operatorMapper;

    @Autowired
    OperatorLogService operatorLogService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @Description: 条件分页查询机构信息
     * @Author: jiy.fang
     * @Date: 2019/7/17 16:15
     */
    @Override
    public BaseResult<DataGrid<OrganizationDTO>> querryOrginazitionByPage(PaginationBO<OrganizationQueryBO> orginazationPageQuery,
                                                                          HttpServletRequest request) throws Exception {
        OrganizationQueryBO organizationQueryBO = orginazationPageQuery.getParams();
        log.info("机构信息查询入参：{}", JSON.toJSONString(organizationQueryBO));
        if (ObjectUtil.isEmpty(organizationQueryBO.getOrgId())) {
            organizationQueryBO.setOrgId(TokenUtil.getOrgId(request.getHeader("token")));
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("orgId", organizationQueryBO.getOrgId());
        queryMap.put("orgName", organizationQueryBO.getOrgName());
        queryMap.put("includeSubOrg", organizationQueryBO.getIncludeSubOrg());
        queryMap.put("updateOrgId", organizationQueryBO.getUpdateOrgId());
        //获取当前机构及下属机构id集合
        List<String> orgIds = getListOrgIds(organizationQueryBO.getOrgId());
        orgIds.add(organizationQueryBO.getOrgId());
        queryMap.put("list", orgIds);
        //设置分页信息
        PageHelper.startPage(orginazationPageQuery.getPageNo(), orginazationPageQuery.getPageSize());
        //执行查询
        List<OrganizationDTO> list = organizationMapper.getListOrganizationDTOByPage(queryMap);
        //总行/一级分行/二级分行/管辖支行/经营性支行
        for (OrganizationDTO organization : list) {
            String orgLevel = String.valueOf(organization.getOrgLevel());
            String orgLevelName = "";
            switch (orgLevel) {
                case "1":
                    orgLevelName = "总行";
                    break;
                case "2":
                    orgLevelName = "一级分行";
                    break;
                case "3":
                    orgLevelName = "二级分行";
                    break;
                case "4":
                    orgLevelName = "管辖支行";
                    break;
                default:
                    orgLevelName = "经营性支行";
            }
            organization.setOrgLevelName(orgLevelName);
        }
        //取分页信息
        PageInfo<OrganizationDTO> pageInfo = new PageInfo<>(list);
        //设置返回结果
        DataGrid<OrganizationDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal((int) total);
        dataGrid.setRows(list);
        return GetResult.getResult(dataGrid);
    }

    /**
     * @Description: 添加机构信息
     * @Author: jiy.fang
     * @Date: 2019/7/18 15:41
     */
    @Override
    public BaseResult insertOrganization(HttpServletRequest request, OrganizationAddBO organizationAddBO,
                                         String orgId, String opId, String opName, List<String> orgList) throws Exception {
        // 由于批量导入时每次都会执行获取操作人员, 所以改为传进来 modified by yangfan 2022/09/28
        // String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        // String opId = TokenUtil.getOpId(request.getHeader("token"));
        // String opName = TokenUtil.getOpName(request.getHeader("token"));
        // 获取父机构信息
        Organization getOrgByPID = organizationMapper.getOrganizationByOrgId(organizationAddBO.getOrgPid());
        if (ObjectUtil.isNull(getOrgByPID)) {
            throw new Exception("上级机构不存在：" + organizationAddBO.getOrgPid());
        }
        //新增子机构 机构级别+1
        organizationAddBO.setOrgLevel(getOrgByPID.getOrgLevel() + 1);

        //定义日志信息
        String logName = TblLogConst.ORG_ADD;
        String operationDesc = "操作人" + opName + "添加了机构：" + organizationAddBO.getOrgName();

        //验证主表中机构名称和机构码是否已经存在
       // int existOrgName = countByOrganizationName(organizationAddBO.getOrgName());
        int existOrgId = countByOrganizationId(organizationAddBO.getOrgId());
        /*if (existOrgName > 0) {
            return GetResult.getResultFail("机构名：" + organizationAddBO.getOrgName() + " 已存在");

        }*/
        if (existOrgId > 0) {
            return GetResult.getResultFail("机构码：" + organizationAddBO.getOrgId() + " 已存在");
        }
        int orgType = Integer.parseInt(organizationAddBO.getOrgType());
        if (orgType > 5){
            return GetResult.getResultFail("机构类型只能是1,2,3,4,5");
        }
        if (StringUtils.isNotBlank(organizationAddBO.getOrgRailSwitch()) && !"0".equals(organizationAddBO.getOrgRailSwitch()) && !"1".equals(organizationAddBO.getOrgRailSwitch())){
            return GetResult.getResultFail("围栏开关只能是0或1");
        }
        // //添加机构时需比对操作员机构,只能添加操作员所属机构的下属机构
        // List<String> orgList = getListOrgIds(orgId);
        // orgList.add(orgId);
        if (!orgList.contains(organizationAddBO.getOrgPid())) {
            return GetResult.getResultFail("添加失败，父级机构应该为该操作员所属机构的子集");
        }
        try {
            ValidatorUtils.beanValidate(organizationAddBO.getOrgWorkingTime());
        } catch (IllegalArgumentException e) {
            return GetResult.getResultFail("开始时间和结束时间不能为空");
        }
        //添加机构主表信息
        Organization organization = new Organization();
        DtoUtils.cloneBeanToBean(organization, organizationAddBO);
        organization.setCreateOp(opId);
        organization.setOrgStatus("0");
        organization.setAuditType(getOrgByPID.getAuditType());
        organization.setOrgLevel(organizationAddBO.getOrgLevel());
        organization.setOrgWorkingTime(JSON.toJSONString(organizationAddBO.getOrgWorkingTime()));
        //添加机构信息
        Integer result = organizationMapper.insertOrg(organization);
        //机构变更，删除缓存
        redisUtils.clearOrgCache();
        redisUtils.clearOrgTreeCache();
        redisUtils.delete("orgtreeid:" + orgId);
        redisUtils.delete("orgid:" + orgId);
        redisUtils.delete("allorgtree");
        if (result > 0) {
            //返回处理结果
            addLogMessage(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("添加成功！");
        }
        return GetResult.getResultSuccess("添加失败！");
    }

    /**
     * @Description: 批量添加机构信息
     * @Author: jiy.fang
     * @Date: 2019/7/18 15:41
     */
    @Override
    public BaseResult insertBatchOrganization(OrganizationAddBO organizationAddBO,
                                         String orgId, String opId, String opName,
                                              List<String> orgList, List<SysLog> logList) throws Exception {
        // 由于批量导入时每次都会执行获取操作人员, 所以改为传进来 modified by yangfan 2022/09/28
        // String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        // String opId = TokenUtil.getOpId(request.getHeader("token"));
        // String opName = TokenUtil.getOpName(request.getHeader("token"));
        // 获取父机构信息
        Organization getOrgByPID = organizationMapper.getOrganizationByOrgId(organizationAddBO.getOrgPid());
        if (ObjectUtil.isNull(getOrgByPID)) {
            throw new Exception("上级机构不存在：" + organizationAddBO.getOrgPid());
        }
        //新增子机构 机构级别+1
        organizationAddBO.setOrgLevel(getOrgByPID.getOrgLevel() + 1);

        //定义日志信息
        String logName = "添加机构";
        String operationDesc = "操作人" + opName + "添加了机构：" + organizationAddBO.getOrgName();

        //验证主表中机构名称和机构码是否已经存在
        //int existOrgName = countByOrganizationName(organizationAddBO.getOrgName());
        int existOrgId = countByOrganizationId(organizationAddBO.getOrgId());
        /*if (existOrgName > 0) {
            return GetResult.getResultFail("机构名：" + organizationAddBO.getOrgName() + " 已存在");

        }*/
        if (existOrgId > 0) {
            return GetResult.getResultFail("机构码：" + organizationAddBO.getOrgId() + " 已存在");
        }
        int orgType = Integer.parseInt(organizationAddBO.getOrgType());
        if (orgType > 5){
            return GetResult.getResultFail("机构类型只能是1,2,3,4,5");
        }
        if (StringUtils.isNotBlank(organizationAddBO.getOrgRailSwitch()) && !"0".equals(organizationAddBO.getOrgRailSwitch()) && !"1".equals(organizationAddBO.getOrgRailSwitch())){
            return GetResult.getResultFail("围栏开关只能是0或1");
        }
        // //添加机构时需比对操作员机构,只能添加操作员所属机构的下属机构
        // List<String> orgList = getListOrgIds(orgId);
        // orgList.add(orgId);
        if (!orgList.contains(organizationAddBO.getOrgPid())) {
            return GetResult.getResultFail("添加失败，父级机构应该为该操作员所属机构的子集");
        }
        try {
            ValidatorUtils.beanValidate(organizationAddBO.getOrgWorkingTime());
        } catch (IllegalArgumentException e) {
            return GetResult.getResultFail("开始时间和结束时间不能为空");
        }
        //添加机构主表信息
        Organization organization = new Organization();
        DtoUtils.cloneBeanToBean(organization, organizationAddBO);
        organization.setCreateOp(opId);
        organization.setOrgStatus("0");
        organization.setAuditType(getOrgByPID.getAuditType());
        organization.setOrgLevel(organizationAddBO.getOrgLevel());
        organization.setOrgWorkingTime(JSON.toJSONString(organizationAddBO.getOrgWorkingTime()));
        //添加机构信息
        Integer result = organizationMapper.insertOrg(organization);
        //机构变更，删除缓存
        redisUtils.clearOrgCache();
        redisUtils.clearOrgTreeCache();
        redisUtils.delete("orgtreeid:" + orgId);
        redisUtils.delete("orgid:" + orgId);
        redisUtils.delete("allorgtree");

        if (result > 0) {
            //返回处理结果
            SysLog sysLog = setLogMessage(operationDesc, logName, "1", opId, opName, orgId);
            logList.add(sysLog);
            return GetResult.getResultSuccess("添加成功！");
        }
        return GetResult.getResultSuccess("添加失败！");
    }

    /**
     * @Description: 修改机构信息
     * @Author: jiy.fang
     * @Date: 2019/7/18 20:41
     */
    @Override
    public BaseResult updateOrganization(HttpServletRequest request, OrganizationUpdateBO organizationUpdateBO) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        Organization organizationOriginal = organizationMapper.getOrganizationById(organizationUpdateBO.getId());
        if(null==organizationOriginal){
            return GetResult.getResultFail("该机构不存在");
        }
        //定义日志信息
        String logName = TblLogConst.ORG_UPDATE;
        String operationDesc = "操作人" + opName + "修改了机构：" + organizationUpdateBO.getOrgName();

        /*if (!organizationOriginal.getOrgName().equals(organizationUpdateBO.getOrgName())) {
            //检查机构名称
            int existOrgName = countByOrganizationName(organizationUpdateBO.getOrgName());
            if (existOrgName > 0) {
                return GetResult.getResultFail("机构名已存在");
            }
        }*/
        //是否修改了上级机构
        List<Organization> children=null;
        //List<Organization> childListOrgByOrgId =null;
        if(StrUtil.isNotBlank(organizationUpdateBO.getOrgPid()) && !organizationOriginal.getOrgPid().equals(organizationUpdateBO.getOrgPid())){
            if("0".equals(organizationOriginal.getOrgPid())){
                return GetResult.getResultFail("不能修改最上级机构的父机构");
            }
            //查询本级及下级机构
           children = getOrgIds(organizationUpdateBO.getOrgId());
            List<String> orgIds = children.stream().map(Organization::getOrgId).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(orgIds) && orgIds.contains(organizationUpdateBO.getOrgPid()) ){
                return GetResult.getResultFail("不能将上级机构修改为本级机构和当前子机构");
            }
            Organization pOrg = organizationMapper.getOrganizationByOrgId(organizationUpdateBO.getOrgPid());
            if(null==pOrg){
                return GetResult.getResultFail("上级机构不存在");
            }
            //计算层级修改前后差值，并同步修改所有子机构
            int newLevel=pOrg.getOrgLevel()+1;
            int oldLevel=organizationOriginal.getOrgLevel();
            int difference=newLevel-oldLevel;
            organizationUpdateBO.setOrgLevel(String.valueOf(newLevel) );

            //去除本级机构
            children.removeIf(org->org.getId().equals(organizationUpdateBO.getId()));
            for(Organization child:children){
                child.setOrgLevel(child.getOrgLevel()+difference);
            }
        }

        if (!organizationOriginal.getOrgId().equals(organizationUpdateBO.getOrgId())) {
            //检查机构名称
            int existOrgId = countByOrganizationId(organizationUpdateBO.getOrgId());
            if (existOrgId > 0) {
                return GetResult.getResultFail("机构码已存在");
            } else {
                List<String> orgIds = new ArrayList<>();
                orgIds.add(organizationOriginal.getOrgId());
                //如果要修改机构码需要先 清空机构下的人员、任务、设备
                int operatorCountByOrgId = operatorMapper.getOperatorCountByOrgId(orgIds);
                if (operatorCountByOrgId > 0) {
                    return GetResult.getResultFail("该机构下存在人员信息，不能修改机构码");
                }
                int taskCountByOrgId = taskMapper.getTaskCountByOrgId(orgIds);
                if (taskCountByOrgId > 0) {
                    return GetResult.getResultFail("该机构下存在任务信息，不能修改机构码");
                }
                int terminalCountByOrgId = terminalMapper.getTerminalCountByOrgId(orgIds);
                if (terminalCountByOrgId > 0) {
                    return GetResult.getResultFail("该机构下存在设备信息，不能修改机构码");
                }
                List<Car> carList = carMapper.getCarInfoByOrg(orgId);
                if (!carList.isEmpty()) {
                    return GetResult.getResultFail("该机构下存在车辆信息，不能修改机构码");
                }
                //childListOrgByOrgId = organizationMapper.getListByPid(organizationOriginal.getOrgId());

            }
        }


        //机构类型修改
        if(!organizationOriginal.getOrgType().equals(organizationUpdateBO.getOrgType())){
            List<String> orgIds = new ArrayList<>();
            orgIds.add(organizationOriginal.getOrgId());
            //如果要修改机构码需要先 清空机构下的人员、任务、设备
            int operatorCountByOrgId = operatorMapper.getOperatorCountByOrgId(orgIds);
            if (operatorCountByOrgId > 0) {
                return GetResult.getResultFail("该机构下存在人员信息，不能修改机构类型");
            }
            int taskCountByOrgId = taskMapper.getTaskCountByOrgId(orgIds);
            if (taskCountByOrgId > 0) {
                return GetResult.getResultFail("该机构下存在任务信息，不能修改机构类型");
            }
            int terminalCountByOrgId = terminalMapper.getTerminalCountByOrgId(orgIds);
            if (terminalCountByOrgId > 0) {
                return GetResult.getResultFail("该机构下存在设备信息，不能修改机构类型");
            }
            List<Car> carList = carMapper.getCarInfoByOrg(orgId);
            if (!carList.isEmpty()) {
                return GetResult.getResultFail("该机构下存在车辆信息，不能修改机构类型");
            }
        }

//        Organization organization = organizationMapper.getOrganizationById(organizationUpdateBO.getId());
        DtoUtils.cloneBeanToBean(organizationOriginal, organizationUpdateBO);
        organizationOriginal.setOrgWorkingTime(JSON.toJSONString(organizationUpdateBO.getOrgWorkingTime()));
        Integer org = organizationMapper.updateOrg(organizationOriginal);
        if (org <= 0) {
            return GetResult.getResultFail("修改失败");
        }
        if(CollectionUtil.isNotEmpty(children)){
            for (Organization child:children){
                Integer update = organizationMapper.updateOrg(child);
                if(update<=0){
                    return GetResult.getResultFail("修改失败");
                }
            }

        }
        //if(CollectionUtil.isNotEmpty(childListOrgByOrgId)){
        //    for (Organization child:childListOrgByOrgId){
        //        child.setOrgPid(organizationUpdateBO.getOrgId());
        //        Integer update = organizationMapper.updateOrg(child);
        //        if(update<=0){
        //            return GetResult.getResultFail("修改失败");
        //        }
        //    }
        //
        //}
        //机构变更，删除缓存
        redisUtils.clearOrgCache();
        redisUtils.clearOrgTreeCache();
        redisUtils.clearOrgTreeCacheAllorgtree();
        addLogMessage(operationDesc, logName, "1", opId, opName, orgId);
        return GetResult.getResultSuccess("修改成功");
    }

    /**
     * @Description: 删除机构
     * @Author: jiy.fang
     * @Date: 2019/7/19 14:09
     */
    @Override
    public BaseResult deleteOrganization(HttpServletRequest request, OrganizationDeleteBO organizationDeleteBO) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String operatorOrgId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        //判断是否能够删除机构
        String orgId = organizationDeleteBO.getOrgId();
        //定义日志信息
        String logName = TblLogConst.ORG_DELETE;
        String operationDesc = "操作人" + opName + "删除了机构：" + organizationDeleteBO.getOrgId();

        //是否存在属于该机构的用户
        List<String> orgIds = new ArrayList<>();
        orgIds.add(orgId);
        int count = operatorMapper.getOperatorCountByOrgId(orgIds);
        //如果要修改机构码需要先清空机构下的人员、任务、设备
        if (count > 0) {
            return GetResult.getResultFail("该机构下存在人员信息，删除机构失败");
        }
        //是否存在子机构
        List<Organization> organizationList = organizationMapper.getChildListOrgByOrgId(orgId);
        if (!organizationList.isEmpty()) {
            return GetResult.getResultFail("存在该机构的子机构，删除机构失败");
        }
        int taskCountByOrgId = taskMapper.getTaskCountByOrgId(orgIds);
        if (taskCountByOrgId > 0) {
            return GetResult.getResultFail("该机构下存在任务信息，删除机构失败");
        }
        int terminalCountByOrgId = terminalMapper.getTerminalCountByOrgId(orgIds);
        if (terminalCountByOrgId > 0) {
            return GetResult.getResultFail("该机构下存在设备信息，删除机构失败");
        }
        List<Car> carList = carMapper.getCarInfoByOrg(orgId);
        if (!carList.isEmpty()) {
            return GetResult.getResultFail("该机构下存在车辆信息，删除机构失败");
        }
        Organization organization = organizationMapper.getOrganizationByOrgId(orgId);
        //机构变更，删除缓存
        redisUtils.clearOrgCache();
        redisUtils.clearPopedomListByOrgId(organization.getOrgId());
        redisUtils.clearOrgTreeCacheAllorgtree();
        //逻辑删除
        Integer result = organizationMapper.deleteOrg(organization.getOrgId());
        //删除该机构的用户
        operatorMapper.deleteOperatorByOrgId(organization.getOrgId());
        //返回操作结果
        if (result <= 0) {
            return GetResult.getResultFail("删除失败");
        }
        addLogMessage(operationDesc, logName, "1", opId, opName, operatorOrgId);
        return GetResult.getResultSuccess("删除成功");
    }

    @Override
    public BaseResult batchDeleteOrg(HttpServletRequest request, OrganizationDeleteBO deleteBO) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String[] orgIds = deleteBO.getOrgId().split(",");
        for (String organizationId : orgIds) {
            OrganizationDeleteBO organizationDeleteBO = new OrganizationDeleteBO();
            BeanUtil.copyProperties(deleteBO, organizationDeleteBO);
            organizationDeleteBO.setOrgId(organizationId);
            BaseResult result = deleteOrganization(request, organizationDeleteBO);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        redisUtils.delete("orgtreeid:" + orgId);
        redisUtils.delete("orgid:" + orgId);
        redisUtils.delete("allorgtree");
        return GetResult.getResultSuccess("删除成功!");
    }

    //添加日志
    private void addLogMessage(String operationDesc, String logName, String logStatus, String opId, String opName, String orgId) {
        operatorLogService.insert(operationDesc, logName, logStatus, opId, opName, orgId);
    }

    /**
     * 组装日志
     */
    private SysLog setLogMessage(String operationDesc, String logName, String logStatus, String opId, String opName, String orgId) {
        SysLog sysLog = new SysLog();
        sysLog.setOperationDesc(operationDesc);
        sysLog.setLogName(logName);
        sysLog.setLogStatus(logStatus);
        sysLog.setOpId(opId);
        sysLog.setOpName(opName);
        sysLog.setOrgId(orgId);
        sysLog.setCreateDatetime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, new Date()));
        return sysLog;
    }

    /**
     * @Description: 获取当前机构及所有子机构
     * @Author: jiy.fang
     * @Date: 2019/7/22 23:01
     */
    @Override
    public List<Organization> getOrgIds(String orgId)  {
        List<String> list = getOrgIdsByOrgId(orgId);
        return organizationMapper.getOrgAndAllSonOrgs(list);
    }

    @Override
    public List<String> getOrgIdsByOrgId(String orgId) {
        Integer level = organizationMapper.getOrgLevelByOrgId(orgId);
        List<Organization> sonOrgs = organizationMapper.getSonOrgs(orgId, level);
        ArrayList list = new ArrayList();
        getOrgIds(sonOrgs,orgId,list);
        list.add(orgId);
        return list;
    }

    public void getOrgIds(List<Organization> orgs, String orgId, List list){
        for (Organization org : orgs) {
            if (StringUtils.isNotBlank(org.getOrgPid())){
                if (org.getOrgPid().equals(orgId)){
                    list.add(org.getOrgId());
                    getOrgIds(orgs,org.getOrgId(),list);
                }
            }
        }
    }



    /**
     * @Description: 获取本机构上下级ID
     * @Author: huix.Liang
     * @Date: 2019-08-06 16:19
     */
    @Override
    public List<Organization> getAllLevelOrgIds(HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        List<String> orgIdList = new ArrayList<>();
        getListOrgId(orgIdList, orgId, true);
        //根据id获取机构名
        return organizationMapper.getListOrganization(orgIdList);
    }

    @Override
    public List<OrganizationDTO> getListOrganizationExport(OrganizationQueryBO organizationQueryBO, HttpServletRequest request) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (null == organizationQueryBO.getOrgId() || "".equals(organizationQueryBO.getOrgId())) {
            organizationQueryBO.setOrgId(orgId);
        }
        //获取子机构码列表
        List<String> orgIdsList;
        orgIdsList = getListOrgIds(orgId);
        orgIdsList.add(orgId);
        organizationQueryBO.setOrgIdsList(orgIdsList);
        return organizationMapper.getListOrganizationDTO(organizationQueryBO);
    }

    /**
     * @Description: 检查主表中机构码是否已经存在
     * @Author: jiy.fang
     * @Date: 2019/7/18 16:51
     */
    private int countByOrganizationId(String orgId) {
        return organizationMapper.getCountByOrgId(orgId);
    }

    /**
     * @Description: 检查主表中机构名是否重复
     * @Author: jiy.fang
     * @Date: 2019/7/18 16:32
     */
    private int countByOrganizationName(String orgName) {
        return organizationMapper.CountByOrgName(orgName);
    }

    @Override
    public BaseResult configSysPermission(HttpServletRequest request, SysPermissionBo sysPermissionBo) {
        // 审核类型 1-同步审核 2-异步审核 null-无审核
        String auditType = "";
        if ("1".equals(sysPermissionBo.getAuditType())){
            auditType = "同步审核";
        }else if ("2".equals(sysPermissionBo.getAuditType())){
            auditType = "异步审核";
        }else {
            auditType = "无审核";
        }
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        Role role = roleMapper.getRoleByRoleId(sysPermissionBo.getRoleId());
        //定义日志信息
        String logName = "系统权限";
        Organization organization = organizationMapper.getOrganizationByOrgId(sysPermissionBo.getOrgId());
        String operationDesc = "操作人" + opName + "将机构" + organization.getOrgName() + "的权限配置为" + auditType;
        if (!"超级管理员".equals(role.getRoleName())) {
            return GetResult.getResultFail("当前用户没有权限操作 ！");
        }
        List<String> orgIds = getListOrgIds(orgId);
        orgIds.add(orgId);
        sysPermissionBo.setOrgIdList(orgIds);
        int result = organizationMapper.updateOrgAuditType(sysPermissionBo);
        if (result > 0) {
            addLogMessage(operationDesc, logName, "1", opId, opName, orgId);
//            //强制退出登录
//            RedisUtil.del("login:operator:"+ opName);
            return GetResult.getResultSuccess("审核方式修改成功！");
        }
        return GetResult.getResultErr("审核方式修改失败！");
    }


    @Override
    public BaseResult<SysPermissionDTO> querySysPermission(HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Organization organization = organizationMapper.getOrganizationByOrgId(orgId);
        SysPermissionDTO sysPermissionDTO = new SysPermissionDTO();
        sysPermissionDTO.setAuditType(organization.getAuditType());
        return GetResult.getResult(sysPermissionDTO);
    }

    /**
     * @Description: 根据机构号查询所有上级、下级机构号
     * @Author: huix.Liang
     * @Date: 2019-07-23 10:46
     */
    @Override
    public void getListOrgId(List<String> orgIdList, String orgId, boolean includeParentOrg) {
        //判断是否是一级机构
        Organization organization = organizationMapper.getOrganizationByOrgId(orgId);

        orgIdList.add(organization.getOrgId());
        //根据父ID递归查询子机构
        recursiveGetOrgId(orgIdList, organization.getOrgId());
        if (includeParentOrg && !"0".equals(organization.getOrgPid())) {
            //不是一级机构, 则递归查询上级机构
            recursionForParentOrg(orgIdList, organization.getOrgId());
        }
    }


    /**
     * @Description: 根据角色类型获取机构信息
     * @Author: jiy.fang
     * @Date: 2019/8/2 9:57
     */
    @Deprecated
    @Override
    public List<Organization> getOrgIdsByRoleType(HttpSession session, int roleType) throws Exception {
//        List<String> orgIds = new ArrayList<>();
//        if (roleType == 1) {
//            //通用角色查询所有机构
//            orgIds.add(jsrcuBankOrg);
//        } else {
//            //普通角色查询所有非信雅达机构
//            Operator operator = (Operator) session.getAttribute(SessionConstants.OPERATOR);
//            orgIds = getListOrgIds(operator.getOrgId());
//            orgIds.add(operator.getOrgId());
//        }
//        return organizationMapper.getListOrganization(orgIds);
        return null;
    }

    @Override
    public BaseResult<List<OrgTreeDTO>> obtainOrgTree(String orgId) throws Exception {
        String strkey = "orgtreeid:" + orgId;
        List<OrgTreeDTO> orgTree = redisUtils.get(strkey, List.class);
        if (orgTree == null || orgTree.size() <= 0) {
            //获取所有机构
            List<OrgTreeDTO> allList = organizationMapper.getAllOrg();
            List<OrgTreeDTO> orgTreeDTOList = organizationMapper.obtainOrg(orgId);
            for (OrgTreeDTO orgTreeDTO : orgTreeDTOList) {
                getAllChild(orgTreeDTO, allList);
            }
            orgTree = orgTreeDTOList;
            redisUtils.set(strkey, orgTree);
        }
        return GetResult.getResult(orgTree);
    }


    @Override
    public BaseResult<List<OrgTreeDTO>> getAllOrgTree() {
        String strkey = "allorgtree";
        List<OrgTreeDTO> orgTree = redisUtils.get(strkey, List.class);
        if (orgTree == null || orgTree.size() <= 0) {
            //获取所有机构
            List<OrgTreeDTO> allList = organizationMapper.getAllOrg();
            orgTree = getAllTree(allList);
            redisUtils.set(strkey, orgTree);
        }
        return GetResult.getResult(orgTree);
    }

    @Override
    public List<String> getListOrgIds(String orgId) {
        String strkey = "orgid:" + orgId;
        List<String> lists = null;
        lists = redisUtils.get(strkey, List.class);
        if (lists == null) {
            lists = new ArrayList<>();
            recursiveGetOrgId(lists, orgId);
        }

        return lists;
    }

    //递归查询子机构
    private void recursiveGetOrgId(List<String> lists, String orgId) {
        List<String> orgIdList = organizationMapper.getOrgIdsList(orgId);
        while (orgIdList.isEmpty()) {
            return;
        }
        orgIdList.forEach(childOrgId -> {
            lists.add(childOrgId);
            recursiveGetOrgId(lists, childOrgId);
        });
    }

    /**
     * 生成树结构
     *
     * @return List<OrganizationDTO>
     */
    private static List<OrgTreeDTO> getAllTree(List<OrgTreeDTO> all) {
        List<OrgTreeDTO> orgTreeDTOList = all.stream().filter(orgTreeDTO -> "0".equals(orgTreeDTO.getOrgPid())).collect(Collectors.toList());
        for (OrgTreeDTO orgTreeDTO : orgTreeDTOList) {
            getAllChild(orgTreeDTO, all);
        }
        return orgTreeDTOList;
    }

    private static void getAllChild(OrgTreeDTO orgTreeDTO, List<OrgTreeDTO> all) {
        // 子机构
        List<OrgTreeDTO> childList = new ArrayList<>();
        for (OrgTreeDTO orgTreeDTO1 : all) {
            // 遍历所有节点，将父机构id与传过来的id比较
            if (StringUtils.isNotBlank(orgTreeDTO.getOrgId())) {
                if (orgTreeDTO1.getOrgPid().equals(orgTreeDTO.getOrgId())) {
                    childList.add(orgTreeDTO1);
                    orgTreeDTO.setChildrenOrg(childList);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (OrgTreeDTO orgTreeDTO1 : childList) {
            getAllChild(orgTreeDTO1, all);
        } // 递归退出条件
        if (childList.isEmpty()) {
            return;
        }
    }

    @Override
    public List<Organization> getOrganizationIdsByOp(HttpServletRequest request) {
        List<Organization> orgIds = new ArrayList<>();
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        List<Organization> list = organizationMapper.getChildListOrgByOrgId(orgId);
        Organization organization = organizationMapper.getOrganizationByOrgId(orgId);
        organization.setChildren(list);
        orgIds.add(organization);
        return orgIds;
    }

    @Override
    public List<Organization> getChildOrgIds(String orgId) {
        return organizationMapper.getChildListOrgByOrgId(orgId);
    }


    /**
     * @Description: 递归查询父级机构
     * @Author: huix.Liang
     * @Date: 2019-07-23 16:25
     */
    private void recursionForParentOrg(List<String> list, String orgId) {
        //根据机构编号去查询父机构
        Organization organization = organizationMapper.getOrganizationByOrgId(orgId);
        list.add(organization.getOrgPid());
        if (!"0".equals(organization.getOrgPid())) {
            //不是一级机构，有父级，则继续查询
            recursionForParentOrg(list, organization.getOrgPid());
        }
        return;
    }

}
